module utils.CommonTool;

/** 
 * 公共工具类
 */
class CommonTool
{

    /** 
     * 获取html源码
     * Params:
     *   url  =  string  =  url地址
     * Returns: string
     */
    public static string getHtml(string url)
    {
        import requests;

        Request req = Request();
        req.sslSetVerifyPeer(false);
        string[string] agentHeader = [
            "User-Agent": CommonTool.getOneUserAgent()
        ];
        req.addHeaders(agentHeader);
        Response res = req.get(url);
        if (res.code == 200)
        {
            return cast(string) res.responseBody;
        }
        return null;
    }

    /** 
     * 取一个user agent
     * Returns: string
     */
    private static string getOneUserAgent()
    {
        import std.random : MinstdRand0, choice;

        string[] userAgents = [
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.169.400 QQBrowser/11.0.5130.400",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36 Edg/103.0.1264.44"
        ];
        auto rnd = MinstdRand0(42);
        return choice(userAgents, rnd);
    }

}
